const express = require('express');
const router = express.Router();
const { authMiddleware } = require('../middleware/auth');
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

// 获取历史日报列表
router.get('/daily/history', authMiddleware, async (req, res) => {
  try {
    // 获取最近30天的日期
    const endDate = new Date();
    endDate.setHours(23, 59, 59, 999);
    
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - 30);
    startDate.setHours(0, 0, 0, 0);
    
    // 使用标准Prisma查询而不是原始SQL
    const orders = await prisma.order.findMany({
      where: {
        createdAt: {
          gte: startDate,
          lte: endDate
        },
        status: {
          in: ['completed', 'paid']
        }
      },
      select: {
        id: true,
        createdAt: true,
        total: true,
        channelId: true,
        channel: true
      }
    });
    
    // 按日期分组统计
    const dailyMap = {};
    
    orders.forEach(order => {
      const dateStr = order.createdAt.toISOString().split('T')[0];
      
      if (!dailyMap[dateStr]) {
        dailyMap[dateStr] = {
          date: dateStr,
          orderCount: 0,
          totalSales: 0,
          channelMap: {} // 添加渠道统计
        };
      }
      
      dailyMap[dateStr].orderCount += 1;
      dailyMap[dateStr].totalSales += order.total;
      
      // 统计渠道数据
      const channelId = order.channelId || 0;
      const channelName = order.channel ? order.channel.name : '未知渠道';
      
      if (!dailyMap[dateStr].channelMap[channelId]) {
        dailyMap[dateStr].channelMap[channelId] = {
          id: channelId,
          name: channelName,
          amount: 0,
          orderCount: 0
        };
      }
      
      dailyMap[dateStr].channelMap[channelId].amount += order.total;
      dailyMap[dateStr].channelMap[channelId].orderCount += 1;
    });
    
    // 转换为数组并排序
    const historyReports = Object.values(dailyMap)
      .map(report => {
        // 将渠道映射转换为数组
        const channelSales = Object.values(report.channelMap);
        delete report.channelMap;
        
        return {
          ...report,
          averageOrder: report.orderCount > 0 ? report.totalSales / report.orderCount : 0,
          channelSales // 添加渠道销售数据
        };
      })
      .sort((a, b) => b.date.localeCompare(a.date));
    
    res.json({
      status: 'success',
      data: historyReports
    });
  } catch (error) {
    console.error('获取历史日报失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取历史日报失败',
      error: error.message
    });
  }
});

// 获取特定日期的日报数据
router.get('/daily/:date', authMiddleware, async (req, res) => {
  try {
    const { date } = req.params;
    
    // 验证日期格式
    if (!date.match(/^\d{4}-\d{2}-\d{2}$/)) {
      return res.status(400).json({
        status: 'error',
        message: '无效的日期格式，请使用YYYY-MM-DD格式'
      });
    }
    
    // 解析日期
    const startDate = new Date(date);
    
    // 检查日期是否有效
    if (isNaN(startDate.getTime())) {
      return res.status(400).json({
        status: 'error',
        message: '无效的日期'
      });
    }
    
    startDate.setHours(0, 0, 0, 0);
    
    const endDate = new Date(startDate);
    endDate.setHours(23, 59, 59, 999);
    
    // 查询该日期的订单
    const orders = await prisma.order.findMany({
      where: {
        createdAt: {
          gte: startDate,
          lte: endDate
        },
        status: {
          in: ['completed', 'paid']
        }
      },
      include: {
        items: {
          include: {
            product: true
          }
        },
        channel: true
      }
    });
    
    // 计算基本统计数据
    const orderCount = orders.length;
    const totalSales = orders.reduce((sum, order) => sum + order.total, 0);
    const averageOrder = orderCount > 0 ? totalSales / orderCount : 0;
    
    // 按支付方式统计
    const paymentMethods = {};
    
    // 获取订单的支付方式
    const orderPayments = await prisma.payment.findMany({
      where: {
        orderId: {
          in: orders.map(order => order.id)
        }
      }
    });
    
    orderPayments.forEach(payment => {
      const method = payment.method || 'unknown';
      paymentMethods[method] = (paymentMethods[method] || 0) + payment.amount;
    });
    
    // 按渠道统计
    const channelMap = {};
    orders.forEach(order => {
      const channelId = order.channelId || 0;
      const channelName = order.channel ? order.channel.name : '未知渠道';
      
      if (!channelMap[channelId]) {
        channelMap[channelId] = {
          id: channelId,
          name: channelName,
          amount: 0,
          orderCount: 0
        };
      }
      
      channelMap[channelId].amount += order.total;
      channelMap[channelId].orderCount += 1;
    });
    const channelSales = Object.values(channelMap);
    
    // 按小时统计
    const hourlyMap = {};
    console.log('开始按小时统计订单，总订单数:', orders.length);
    
    orders.forEach(order => {
      // 记录原始时间
      const orderCreatedAt = order.createdAt;
      console.log(`订单ID: ${order.id}, 原始时间字符串:`, orderCreatedAt);
      
      // 解析时间
      let orderDate;
      try {
        // 尝试解析ISO格式
        orderDate = new Date(orderCreatedAt);
        
        // 检查是否为有效日期
        if (isNaN(orderDate.getTime())) {
          console.error(`无效的日期格式: ${orderCreatedAt}`);
          return; // 跳过此订单
        }
        
        // 获取本地时间小时
        const hour = orderDate.getHours();
        const minute = orderDate.getMinutes();
        const second = orderDate.getSeconds();
        
        console.log(`订单ID: ${order.id}, 解析后日期: ${orderDate.toISOString()}, 本地时间: ${hour}:${minute}:${second}, 时区偏移: ${orderDate.getTimezoneOffset()}分钟`);
        
        if (!hourlyMap[hour]) {
          hourlyMap[hour] = {
            hour,
            amount: 0,
            orderCount: 0
          };
        }
        
        hourlyMap[hour].amount += order.total;
        hourlyMap[hour].orderCount += 1;
      } catch (error) {
        console.error(`解析订单时间出错, 订单ID: ${order.id}, 错误:`, error);
      }
    });
    
    // 转换为数组并排序
    const hourlyTrends = Object.values(hourlyMap).sort((a, b) => a.hour - b.hour);
    console.log('hourlyTrends 统计结果:', JSON.stringify(hourlyTrends));
    
    // 计算热销商品
    const productMap = {};
    orders.forEach(order => {
      if (!order.items) return;
      
      order.items.forEach(item => {
        if (!item || !item.product) return;
        
        const productId = item.productId;
        const productName = item.product ? item.product.name : '未知商品';
        
        if (!productMap[productId]) {
          productMap[productId] = {
            id: productId,
            name: productName,
            quantity: 0,
            amount: 0
          };
        }
        
        productMap[productId].quantity += item.quantity;
        productMap[productId].amount += item.price * item.quantity;
      });
    });
    
    // 转换为数组并排序
    let topProducts = Object.values(productMap)
      .sort((a, b) => b.amount - a.amount)
      .slice(0, 10);
    
    // 计算占比
    if (totalSales > 0) {
      topProducts = topProducts.map(product => ({
        ...product,
        percentage: product.amount / totalSales
      }));
    }
    
    res.json({
      status: 'success',
      data: {
        date,
        orderCount,
        totalSales,
        averageOrder,
        paymentMethods,
        channelSales,
        hourlyTrends,
        topProducts
      }
    });
  } catch (error) {
    console.error('获取日报数据失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取日报数据失败',
      error: error.message
    });
  }
});

// 导出日报
router.get('/daily/:date/export', async (req, res) => {
  try {
    const { date } = req.params;
    
    console.log('收到单日普通导出请求，日期参数:', { date });
    
    // 验证日期格式 - 修改为更宽松的验证
    // 允许任何格式的日期字符串，只要能被Date对象解析
    const startDate = new Date(date);
    
    // 检查日期是否有效
    if (isNaN(startDate.getTime())) {
      return res.status(400).json({
        status: 'error',
        message: '无效的日期'
      });
    }
    
    // 格式化日期为YYYY-MM-DD格式
    const formattedDate = startDate.toISOString().split('T')[0];
    
    console.log('格式化后的日期:', { formattedDate });
    
    startDate.setHours(0, 0, 0, 0);
    
    const endDate = new Date(startDate);
    endDate.setHours(23, 59, 59, 999);
    
    // 确保Excel库可用
    let Excel;
    try {
      Excel = require('exceljs');
    } catch (err) {
      console.error('ExcelJS库加载失败:', err);
      return res.status(500).json({
        status: 'error',
        message: '导出功能暂时不可用，请联系管理员'
      });
    }
    
    // 查询该日期的订单
    const orders = await prisma.order.findMany({
      where: {
        createdAt: {
          gte: startDate,
          lte: endDate
        },
        status: {
          in: ['completed', 'paid']
        }
      },
      include: {
        items: {
          include: {
            product: true
          }
        },
        channel: true,
        payments: {
          select: {
            id: true,
            orderId: true,
            method: true,
            amount: true,
            status: true,
            createdAt: true,
            updatedAt: true
          }
        }
      }
    });
    
    // 计算基本统计数据
    const orderCount = orders.length;
    const totalSales = orders.reduce((sum, order) => sum + order.total, 0);
    const averageOrder = orderCount > 0 ? totalSales / orderCount : 0;
    
    // 按支付方式统计
    const paymentMethods = {};
    orders.forEach(order => {
      if (!order.payments) return;
      
      order.payments.forEach(payment => {
        const method = payment.method || 'unknown';
        paymentMethods[method] = (paymentMethods[method] || 0) + payment.amount;
      });
    });
    
    // 按渠道统计
    const channelMap = {};
    orders.forEach(order => {
      const channelId = order.channelId || 0;
      const channelName = order.channel ? order.channel.name : '未知渠道';
      
      if (!channelMap[channelId]) {
        channelMap[channelId] = {
          id: channelId,
          name: channelName,
          amount: 0,
          orderCount: 0
        };
      }
      
      channelMap[channelId].amount += order.total;
      channelMap[channelId].orderCount += 1;
    });
    const channelSales = Object.values(channelMap);
    
    // 计算热销商品
    const productMap = {};
    orders.forEach(order => {
      if (!order.items) return;
      
      order.items.forEach(item => {
        if (!item || !item.product) return;
        
        const productId = item.productId;
        const productName = item.product ? item.product.name : '未知商品';
        
        if (!productMap[productId]) {
          productMap[productId] = {
            id: productId,
            name: productName,
            quantity: 0,
            amount: 0
          };
        }
        
        productMap[productId].quantity += item.quantity;
        productMap[productId].amount += item.price * item.quantity;
      });
    });
    
    // 转换为数组并排序
    const topProducts = Object.values(productMap)
      .sort((a, b) => b.amount - a.amount);
    
    // 创建Excel工作簿和工作表
    const workbook = new Excel.Workbook();
    const worksheet = workbook.addWorksheet('日报数据');
    
    // 添加标题
    worksheet.mergeCells('A1:F1');
    worksheet.getCell('A1').value = `哈喽啤鲜生销售日报 - ${date}`;
    worksheet.getCell('A1').font = { size: 16, bold: true };
    worksheet.getCell('A1').alignment = { horizontal: 'center' };
    
    // 添加基本统计数据
    worksheet.addRow(['基本统计', '', '', '', '', '']);
    worksheet.addRow(['订单数', orderCount, '', '营业额', totalSales.toFixed(2), '元']);
    worksheet.addRow(['客单价', averageOrder.toFixed(2), '元', '', '', '']);
    worksheet.addRow(['', '', '', '', '', '']);
    
    // 添加支付方式统计
    worksheet.addRow(['支付方式统计', '', '', '', '', '']);
    worksheet.addRow(['支付方式', '金额(元)', '', '', '', '']);
    
    const paymentMethodNames = {
      'cash': '现金',
      'wechat': '微信支付',
      'alipay': '支付宝',
      'complimentary': '招待',
      'mixed': '混合支付',
      'unknown': '未知方式'
    };
    
    Object.entries(paymentMethods).forEach(([method, amount]) => {
      worksheet.addRow([paymentMethodNames[method] || method, amount.toFixed(2), '', '', '', '']);
    });
    worksheet.addRow(['', '', '', '', '', '']);
    
    // 添加渠道销售统计
    worksheet.addRow(['渠道销售统计', '', '', '', '', '']);
    worksheet.addRow(['渠道名称', '订单数', '金额(元)', '', '', '']);
    
    channelSales.forEach(channel => {
      worksheet.addRow([channel.name, channel.orderCount, channel.amount.toFixed(2), '', '', '']);
    });
    worksheet.addRow(['', '', '', '', '', '']);
    
    // 添加热销商品统计
    worksheet.addRow(['热销商品统计', '', '', '', '', '']);
    worksheet.addRow(['商品名称', '销售数量', '销售金额(元)', '占比(%)', '', '']);
    
    topProducts.forEach(product => {
      const percentage = totalSales > 0 ? (product.amount / totalSales * 100).toFixed(2) : '0.00';
      worksheet.addRow([product.name, product.quantity, product.amount.toFixed(2), percentage, '', '']);
    });
    
    // 设置列宽
    worksheet.getColumn(1).width = 20;
    worksheet.getColumn(2).width = 15;
    worksheet.getColumn(3).width = 15;
    worksheet.getColumn(4).width = 15;
    
    try {
      // 设置响应头
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      const safeFilename = `哈喽啤鲜生销售日报-${date}.xlsx`;
      res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(safeFilename)}"`);
      res.setHeader('X-Content-Type-Options', 'nosniff');
      
      // 将工作簿写入响应
      await workbook.xlsx.write(res);
    } catch (err) {
      console.error('Excel生成失败:', err);
      return res.status(500).json({
        status: 'error',
        message: '报表生成失败',
        error: err.message
      });
    }
    
  } catch (error) {
    console.error('导出日报失败:', error);
    res.status(500).json({
      status: 'error',
      message: '导出日报失败',
      error: error.message
    });
  }
});

// 获取日销售报表
router.get('/daily', authMiddleware, async (req, res) => {
  try {
    const { date, startDate, endDate } = req.query;
    
    // 处理日期参数 - 日报只查询单日数据
    let reportDate;

    if (startDate) {
      // 如果提供了开始日期，使用开始日期作为报表日期
      reportDate = startDate;
    } else if (date) {
      // 如果提供了单个日期，使用该日期
      reportDate = date;
    } else {
      // 默认使用当天日期
      reportDate = new Date().toISOString().split('T')[0];
    }

    const reportStartDate = new Date(reportDate);
    const reportEndDate = new Date(reportDate);
    
    // 设置时间范围
    reportStartDate.setHours(0, 0, 0, 0);
    reportEndDate.setHours(23, 59, 59, 999);
    
    // 检查日期是否有效
    if (isNaN(reportStartDate.getTime()) || isNaN(reportEndDate.getTime())) {
      return res.status(400).json({
        status: 'error',
        message: '无效的日期格式'
      });
    }
    
    // 查询该日期范围内的所有订单，不仅限于completed和paid状态
    const allOrders = await prisma.order.findMany({
      where: {
        createdAt: {
          gte: reportStartDate,
          lte: reportEndDate
        }
      },
      include: {
        items: {
          include: {
            product: true
          }
        },
        channel: true,
        payments: true,
        user: true
      }
    });
    
    // 筛选有效订单（已完成或已支付）用于销售统计
    const validOrders = allOrders.filter(order => 
      ['completed', 'paid'].includes(order.status)
    );
    
    // 计算基本统计数据
    const orderCount = validOrders.length;
    const totalSales = validOrders.reduce((sum, order) => sum + order.total, 0);
    const averageOrder = orderCount > 0 ? totalSales / orderCount : 0;
    
    // 按渠道统计
    const channelMap = {};
    validOrders.forEach(order => {
      const channelId = order.channelId || 0;
      const channelName = order.channel ? order.channel.name : '未知渠道';
      
      if (!channelMap[channelId]) {
        channelMap[channelId] = {
          channelId,
          channelName,
          amount: 0,
          orders: 0
        };
      }
      
      channelMap[channelId].amount += order.total;
      channelMap[channelId].orders += 1;
    });
    const salesByChannel = Object.values(channelMap);
    
    // 按支付方式统计
    const paymentMethodMap = {};

    // 添加默认支付方式（不查询PaymentMethod表，避免数据库结构问题）
    const defaultMethods = ['cash', 'wechat', 'alipay', 'card', 'member', 'coupon', 'mixed'];
    defaultMethods.forEach(method => {
      if (!paymentMethodMap[method]) {
        paymentMethodMap[method] = {
          method,
          amount: 0,
          count: 0
        };
      }
    });
    
    // 统计每种支付方式的金额和笔数
    validOrders.forEach(order => {
      if (!order.payments || order.payments.length === 0) {
        // 处理没有支付记录的订单
        if (!paymentMethodMap['unknown']) {
          paymentMethodMap['unknown'] = {
            method: 'unknown',
            amount: 0,
            count: 0
          };
        }
        paymentMethodMap['unknown'].amount += order.total;
        paymentMethodMap['unknown'].count += 1;
        return;
      }
      
      // 处理有支付记录的订单
      if (order.payments.length === 1) {
        // 单一支付方式
        const payment = order.payments[0];
        const method = payment.method || 'unknown';
        
        if (!paymentMethodMap[method]) {
          paymentMethodMap[method] = {
            method,
            amount: 0,
            count: 0
          };
        }
        
        paymentMethodMap[method].amount += payment.amount;
        paymentMethodMap[method].count += 1;
      } else if (order.payments.length > 1) {
        // 混合支付方式 - 先标记为混合支付
        if (!paymentMethodMap['mixed']) {
          paymentMethodMap['mixed'] = {
            method: 'mixed',
            amount: 0,
            count: 0
          };
        }
        
        paymentMethodMap['mixed'].amount += order.total;
        paymentMethodMap['mixed'].count += 1;
        
        // 同时也记录每种支付方式的实际金额
        order.payments.forEach(payment => {
          const method = payment.method || 'unknown';
          
          if (!paymentMethodMap[method]) {
            paymentMethodMap[method] = {
              method,
              amount: 0,
              count: 0
            };
          }
          
          paymentMethodMap[method].amount += payment.amount;
          // 不增加count，因为已经在mixed中计数了
        });
      }
    });
    
    // 过滤掉金额为0的支付方式
    const salesByPaymentMethod = Object.values(paymentMethodMap)
      .filter(item => item.amount > 0);
    
    // 计算热销商品
    const productMap = {};
    validOrders.forEach(order => {
      if (!order.items || order.items.length === 0) return;
      
      order.items.forEach(item => {
        if (!item || !item.product) return;
        
        const productId = item.productId;
        const productName = item.product ? item.product.name : '未知商品';
        
        if (!productMap[productId]) {
          productMap[productId] = {
            productId,
            name: productName,
            quantity: 0,
            amount: 0
          };
        }
        
        productMap[productId].quantity += item.quantity;
        productMap[productId].amount += item.price * item.quantity;
      });
    });
    
    // 转换为数组并排序
    const topProducts = Object.values(productMap)
      .sort((a, b) => b.amount - a.amount)
      .slice(0, 10);
    
    // 按小时统计销售趋势
    const hourlyMap = {};
    for (let i = 0; i < 24; i++) {
      hourlyMap[i] = {
        hour: i,
        amount: 0,
        orders: 0
      };
    }
    
    validOrders.forEach(order => {
      const hour = new Date(order.createdAt).getHours();
      hourlyMap[hour].amount += order.total;
      hourlyMap[hour].orders += 1;
    });
    
    const hourlyTrends = Object.values(hourlyMap);
    
    // 按操作员统计
    const operatorMap = {};
    validOrders.forEach(order => {
      const userId = order.userId || 0;
      const userName = order.user ? (order.user.name || order.user.username) : '未知操作员';
      
      if (!operatorMap[userId]) {
        operatorMap[userId] = {
          userId,
          userName,
          amount: 0,
          orders: 0
        };
      }
      
      operatorMap[userId].amount += order.total;
      operatorMap[userId].orders += 1;
    });
    
    const salesByOperator = Object.values(operatorMap);
    
    // 计算退款金额
    const refundOrders = allOrders.filter(order => order.status === 'refunded');
    const refundAmount = refundOrders.reduce((sum, order) => sum + order.total, 0);
    
    // 构造响应数据
    const responseData = {
      date: startDate && endDate ? `${startDate} 至 ${endDate}` : (date || new Date().toISOString().split('T')[0]),
      totalSales,
      totalOrders: orderCount,
      averageOrder,
      refundAmount,
      refundOrders: refundOrders.length,
      salesByChannel,
      salesByPaymentMethod,
      salesByOperator,
      hourlyTrends,
      topProducts,
      // 添加原始订单数据的统计信息
      orderStatus: {
        total: allOrders.length,
        completed: allOrders.filter(o => o.status === 'completed').length,
        paid: allOrders.filter(o => o.status === 'paid').length,
        pending: allOrders.filter(o => o.status === 'pending').length,
        refunded: refundOrders.length,
        other: allOrders.filter(o => !['completed', 'paid', 'pending', 'refunded'].includes(o.status)).length
      }
    };
    
    res.json({
      status: 'success',
      data: responseData
    });
  } catch (error) {
    console.error('获取日销售报表失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取日销售报表失败',
      error: error.message
    });
  }
});

// 获取月销售报表
router.get('/monthly', authMiddleware, async (req, res) => {
  try {
  const { year, month } = req.query;
    
    // 如果没有提供年月，使用当前年月
    const currentDate = new Date();
    const reportYear = parseInt(year) || currentDate.getFullYear();
    const reportMonth = parseInt(month) || currentDate.getMonth() + 1;
    
    // 计算月份的起止日期
    const startDate = new Date(reportYear, reportMonth - 1, 1);
    startDate.setHours(0, 0, 0, 0);
    
    const endDate = new Date(reportYear, reportMonth, 0);
    endDate.setHours(23, 59, 59, 999);
    
    // 查询该月份的订单
    const orders = await prisma.order.findMany({
      where: {
        createdAt: {
          gte: startDate,
          lte: endDate
        },
        status: {
          in: ['completed', 'paid']
        }
      },
      include: {
        items: {
          include: {
            product: true
          }
        },
        channel: true,
        payments: {
          select: {
            id: true,
            orderId: true,
            method: true,
            amount: true,
            status: true,
            createdAt: true,
            updatedAt: true
          }
        }
      }
    });
    
    // 计算基本统计数据
    const orderCount = orders.length;
    const totalSales = orders.reduce((sum, order) => sum + order.total, 0);
    
    // 按日期统计
    const dailySalesMap = {};
    const daysInMonth = new Date(reportYear, reportMonth, 0).getDate();
    
    // 初始化每一天
    for (let day = 1; day <= daysInMonth; day++) {
      dailySalesMap[day] = {
        day,
        amount: 0,
        orders: 0
      };
    }
    
    // 填充实际数据
    orders.forEach(order => {
      const orderDate = new Date(order.createdAt);
      const day = orderDate.getDate();
      
      if (dailySalesMap[day]) {
        dailySalesMap[day].amount += order.total;
        dailySalesMap[day].orders += 1;
      }
    });
    
    // 转换为数组
    const dailySales = Object.values(dailySalesMap);
    
    // 按渠道统计
    const channelMap = {};
    orders.forEach(order => {
      const channelId = order.channelId || 0;
      const channelName = order.channel ? order.channel.name : '未知渠道';
      
      if (!channelMap[channelId]) {
        channelMap[channelId] = {
          channelId,
          channelName,
          amount: 0,
          orders: 0
        };
      }
      
      channelMap[channelId].amount += order.total;
      channelMap[channelId].orders += 1;
    });
    // 修正渠道数据字段名
    const salesByChannel = Object.values(channelMap).map(channel => ({
      channelId: channel.channelId,
      channelName: channel.channelName,
      amount: channel.amount,
      orders: channel.orders
    }));
    
    // 按支付方式统计
    const paymentMethodMap = {};
    orders.forEach(order => {
      if (!order.payments || order.payments.length === 0) return;
      
      order.payments.forEach(payment => {
        const method = payment.method || 'unknown';
        
        if (!paymentMethodMap[method]) {
          paymentMethodMap[method] = {
            method,
            amount: 0,
            count: 0
          };
        }
        
        paymentMethodMap[method].amount += payment.amount;
        paymentMethodMap[method].count += 1;
      });
    });
    // 修正支付方式数据字段名
    const salesByPaymentMethod = Object.values(paymentMethodMap).map(payment => ({
      method: payment.method,
      amount: payment.amount,
      count: payment.count
    }));
    
    // 计算热销商品
    const productMap = {};
    orders.forEach(order => {
      if (!order.items) return;
      
      order.items.forEach(item => {
        if (!item || !item.product) return;
        
        const productId = item.productId;
        const productName = item.product ? item.product.name : '未知商品';
        
        if (!productMap[productId]) {
          productMap[productId] = {
            productId,
            name: productName,
            quantity: 0,
            amount: 0
          };
        }
        
        productMap[productId].quantity += item.quantity;
        productMap[productId].amount += item.price * item.quantity;
      });
    });
    
    // 转换为数组并排序，修正字段名
    const topProducts = Object.values(productMap)
      .map(product => ({
        productId: product.productId,
        productName: product.name, // 修正字段名
        quantity: product.quantity,
        amount: product.amount
      }))
      .sort((a, b) => b.amount - a.amount)
      .slice(0, 10);
    
  res.json({
    status: 'success',
    data: {
        year: reportYear,
        month: reportMonth,
        totalSales,
        orderCount: orderCount, // 修正字段名
        dailySales,
        channelSales: salesByChannel, // 修正字段名
        paymentMethods: salesByPaymentMethod, // 修正字段名
        topProducts
      }
    });
  } catch (error) {
    console.error('获取月销售报表失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取月销售报表失败',
      error: error.message
    });
  }
});

// 获取年销售报表
router.get('/yearly', authMiddleware, async (req, res) => {
  try {
  const { year } = req.query;
    
    // 如果没有提供年份，使用当前年份
    const reportYear = parseInt(year) || new Date().getFullYear();
    
    // 计算年份的起止日期
    const startDate = new Date(reportYear, 0, 1);
    startDate.setHours(0, 0, 0, 0);
    
    const endDate = new Date(reportYear, 11, 31);
    endDate.setHours(23, 59, 59, 999);
    
    // 查询该年份的订单
    const orders = await prisma.order.findMany({
      where: {
        createdAt: {
          gte: startDate,
          lte: endDate
        },
        status: {
          in: ['completed', 'paid']
        }
      },
      include: {
        items: {
          include: {
            product: true
          }
        },
        channel: true,
        payments: {
          select: {
            id: true,
            orderId: true,
            method: true,
            amount: true,
            status: true,
            createdAt: true,
            updatedAt: true
          }
        }
      }
    });
    
    // 计算基本统计数据
    const orderCount = orders.length;
    const totalSales = orders.reduce((sum, order) => sum + order.total, 0);
    
    // 按月份统计
    const monthlySalesMap = {};
    
    // 初始化每个月
    for (let month = 1; month <= 12; month++) {
      monthlySalesMap[month] = {
        month,
        amount: 0,
        orders: 0
      };
    }
    
    // 填充实际数据
    orders.forEach(order => {
      const orderDate = new Date(order.createdAt);
      const month = orderDate.getMonth() + 1; // getMonth() 返回 0-11
      
      if (monthlySalesMap[month]) {
        monthlySalesMap[month].amount += order.total;
        monthlySalesMap[month].orders += 1;
      }
    });
    
    // 转换为数组
    const monthlySales = Object.values(monthlySalesMap);

    // 计算季度销售数据
    const quarterlySales = [
      { quarter: 1, amount: monthlySales.slice(0, 3).reduce((sum, month) => sum + month.amount, 0) },
      { quarter: 2, amount: monthlySales.slice(3, 6).reduce((sum, month) => sum + month.amount, 0) },
      { quarter: 3, amount: monthlySales.slice(6, 9).reduce((sum, month) => sum + month.amount, 0) },
      { quarter: 4, amount: monthlySales.slice(9, 12).reduce((sum, month) => sum + month.amount, 0) }
    ];
    
    // 按渠道统计
    const channelMap = {};
    orders.forEach(order => {
      const channelId = order.channelId || 0;
      const channelName = order.channel ? order.channel.name : '未知渠道';
      
      if (!channelMap[channelId]) {
        channelMap[channelId] = {
          channelId,
          channelName,
          amount: 0,
          orders: 0
        };
      }
      
      channelMap[channelId].amount += order.total;
      channelMap[channelId].orders += 1;
    });
    // 修正渠道数据字段名
    const salesByChannel = Object.values(channelMap).map(channel => ({
      channelId: channel.channelId,
      channelName: channel.channelName,
      amount: channel.amount,
      orders: channel.orders
    }));
    
    // 按支付方式统计
    const paymentMethodMap = {};
    orders.forEach(order => {
      if (!order.payments || order.payments.length === 0) return;
      
      order.payments.forEach(payment => {
        const method = payment.method || 'unknown';
        
        if (!paymentMethodMap[method]) {
          paymentMethodMap[method] = {
            method,
            amount: 0,
            count: 0
          };
        }
        
        paymentMethodMap[method].amount += payment.amount;
        paymentMethodMap[method].count += 1;
      });
    });
    // 修正支付方式数据字段名
    const salesByPaymentMethod = Object.values(paymentMethodMap).map(payment => ({
      method: payment.method,
      amount: payment.amount,
      count: payment.count
    }));
    
    // 计算热销商品
    const productMap = {};
    orders.forEach(order => {
      if (!order.items) return;
      
      order.items.forEach(item => {
        if (!item || !item.product) return;
        
        const productId = item.productId;
        const productName = item.product ? item.product.name : '未知商品';
        
        if (!productMap[productId]) {
          productMap[productId] = {
            productId,
            name: productName,
            quantity: 0,
            amount: 0
          };
        }
        
        productMap[productId].quantity += item.quantity;
        productMap[productId].amount += item.price * item.quantity;
      });
    });
    
    // 转换为数组并排序，修正字段名
    const topProducts = Object.values(productMap)
      .map(product => ({
        productId: product.productId,
        productName: product.name, // 修正字段名
        quantity: product.quantity,
        amount: product.amount
      }))
      .sort((a, b) => b.amount - a.amount)
      .slice(0, 10);
    
  res.json({
    status: 'success',
    data: {
        year: reportYear,
        totalSales,
        orderCount: orderCount, // 修正字段名
        monthlySales,
        quarterlySales, // 添加季度销售数据
        channelSales: salesByChannel, // 修正字段名
        paymentMethods: salesByPaymentMethod, // 修正字段名
        topProducts
      }
    });
  } catch (error) {
    console.error('获取年销售报表失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取年销售报表失败',
      error: error.message
    });
  }
});

// 获取交易明细报表
router.get('/transactions', authMiddleware, async (req, res) => {
  try {
    const { 
      startDate, 
      endDate, 
      page = 1, 
      pageSize = 20, 
      storeId = '', 
      shift = '', 
      receiptType = '', 
      orderNumber = '',
      operatorId = '',
      viewType = 'all' 
    } = req.query;

    if (!startDate || !endDate) {
      return res.status(400).json({
        status: 'error',
        message: '请提供起始日期和结束日期'
      });
    }

    // 验证日期格式
    if (!startDate.match(/^\d{4}-\d{2}-\d{2}$/) || !endDate.match(/^\d{4}-\d{2}-\d{2}$/)) {
      return res.status(400).json({
        status: 'error',
        message: '无效的日期格式，请使用YYYY-MM-DD格式'
      });
    }

    // 解析日期
    const start = new Date(startDate);
    start.setHours(0, 0, 0, 0);

    const end = new Date(endDate);
    end.setHours(23, 59, 59, 999);

    // 检查日期是否有效
    if (isNaN(start.getTime()) || isNaN(end.getTime())) {
      return res.status(400).json({
        status: 'error',
        message: '无效的日期'
      });
    }

    // 构建查询条件
    const where = {
      createdAt: {
        gte: start,
        lte: end
      }
    };

    // 过滤条件：订单号
    if (orderNumber) {
      where.orderNo = {
        contains: orderNumber
      };
    }

    // 过滤条件：门店ID
    if (storeId) {
      // 假设Order表中有storeId字段，或者通过关联查询
      where.storeId = parseInt(storeId);
    }

    // 过滤条件：班次
    if (shift) {
      where.shift = {
        some: {
          type: shift
        }
      };
    }

    // 过滤条件：操作员ID
    if (operatorId) {
      where.userId = parseInt(operatorId);
    }

    // 查询订单总数
    const totalOrders = await prisma.order.count({
      where
    });

    // 查询分页后的订单
    const orders = await prisma.order.findMany({
      where,
      include: {
        user: true,
        payments: {
          select: {
            id: true,
            orderId: true,
            method: true,
            amount: true,
            status: true,
            createdAt: true,
            updatedAt: true
          }
        },
        channel: true,
        shift: true
      },
      skip: (parseInt(page) - 1) * parseInt(pageSize),
      take: parseInt(pageSize),
      orderBy: {
        createdAt: 'desc'
      }
    });

    // 转换为收款明细格式
    const items = orders.map(order => {
      // 获取主要支付方式
      const mainPayment = order.payments && order.payments.length > 0 
        ? order.payments[0] 
        : { method: 'unknown', amount: 0 };
      
      const paymentType = mainPayment.method;
      const isMultiplePayments = order.payments && order.payments.length > 1;

      // 获取操作员信息
      const operatorName = order.user ? order.user.name || order.user.username : '未知';

      // 获取门店信息
      const storeName = ''; // TODO: 添加门店关联
      
      // 格式化日期和时间
      const date = order.createdAt.toISOString().split('T')[0];
      const time = order.createdAt.toISOString().replace('T', ' ').substring(0, 19);

      // 确定收款类型
      let type = 'sale';
      if (order.status === 'refunded') {
        type = 'refund';
      } else if (order.status === 'adjusted') {
        type = 'adjustment';
      }

      return {
        id: order.id,
        receiptId: order.orderNo,
        type,
        amount: order.total,
        paymentType: isMultiplePayments ? 'mixed' : paymentType,
        date,
        time,
        customerName: '', // 顾客信息可能需要额外关联查询
        operatorName,
        shift: order.shift ? order.shift.type : '',
        storeName: order.channel ? order.channel.name : '',
        remark: order.note || ''
      };
    });

    // 如果指定了支付方式过滤
    const filteredItems = viewType && viewType !== 'all'
      ? items.filter(item => item.paymentType === viewType)
      : items;

    // 计算统计信息
    const allItems = await prisma.order.findMany({
      where,
      select: {
        total: true,
        status: true
      }
    });

    const totalAmount = allItems.reduce((sum, item) => sum + item.total, 0);
    const positiveAmount = allItems
      .filter(item => item.status !== 'refunded')
      .reduce((sum, item) => sum + item.total, 0);
    const negativeAmount = allItems
      .filter(item => item.status === 'refunded')
      .reduce((sum, item) => sum + item.total, 0);

    // 返回数据
    res.json({
      status: 'success',
      data: {
        items: filteredItems,
        total: filteredItems.length,
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        totalPages: Math.ceil(filteredItems.length / parseInt(pageSize)),
        dateRange: [startDate, endDate],
        statistics: {
          totalAmount,
          positiveAmount,
          negativeAmount,
          receiptCount: allItems.length
        }
      }
    });
  } catch (error) {
    console.error('获取交易明细失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取交易明细失败',
      error: error.message
    });
  }
});

// 导出交易明细报表
router.get('/transactions/export', async (req, res) => {
  try {
    const { 
      startDate, 
      endDate, 
      storeId = '', 
      shift = '', 
      receiptType = '', 
      orderNumber = '',
      operatorId = '',
      viewType = 'all' 
    } = req.query;

    if (!startDate || !endDate) {
      return res.status(400).json({
        status: 'error',
        message: '请提供起始日期和结束日期'
      });
    }

    // 验证日期格式
    if (!startDate.match(/^\d{4}-\d{2}-\d{2}$/) || !endDate.match(/^\d{4}-\d{2}-\d{2}$/)) {
      return res.status(400).json({
        status: 'error',
        message: '无效的日期格式，请使用YYYY-MM-DD格式'
      });
    }

    // 解析日期
    const start = new Date(startDate);
    start.setHours(0, 0, 0, 0);

    const end = new Date(endDate);
    end.setHours(23, 59, 59, 999);

    // 检查日期是否有效
    if (isNaN(start.getTime()) || isNaN(end.getTime())) {
      return res.status(400).json({
        status: 'error',
        message: '无效的日期'
      });
    }

    // 构建查询条件
    const where = {
      createdAt: {
        gte: start,
        lte: end
      }
    };

    // 过滤条件：订单号
    if (orderNumber) {
      where.orderNo = {
        contains: orderNumber
      };
    }

    // 过滤条件：门店ID
    if (storeId) {
      // 假设Order表中有storeId字段，或者通过关联查询
      where.storeId = parseInt(storeId);
    }

    // 过滤条件：班次
    if (shift) {
      where.shift = {
        some: {
          type: shift
        }
      };
    }

    // 过滤条件：操作员ID
    if (operatorId) {
      where.userId = parseInt(operatorId);
    }

    // 确保Excel库可用
    let Excel;
    try {
      Excel = require('exceljs');
    } catch (err) {
      console.error('ExcelJS库加载失败:', err);
      return res.status(500).json({
        status: 'error',
        message: '导出功能暂时不可用，请联系管理员'
      });
    }

    // 查询所有符合条件的订单
    const orders = await prisma.order.findMany({
      where,
      include: {
        user: true,
        payments: true,
        channel: true,
        shift: true
      },
      orderBy: {
        createdAt: 'desc'
      }
    });

    // 转换为收款明细格式
    let items = orders.map(order => {
      // 获取主要支付方式
      const mainPayment = order.payments && order.payments.length > 0 
        ? order.payments[0] 
        : { method: 'unknown', amount: 0 };
      
      const paymentType = mainPayment.method;
      const isMultiplePayments = order.payments && order.payments.length > 1;

      // 获取操作员信息
      const operatorName = order.user ? order.user.name || order.user.username : '未知';
      
      // 格式化日期和时间
      const date = order.createdAt.toISOString().split('T')[0];
      const time = order.createdAt.toISOString().replace('T', ' ').substring(0, 19);

      // 确定收款类型
      let type = 'sale';
      if (order.status === 'refunded') {
        type = 'refund';
      } else if (order.status === 'adjusted') {
        type = 'adjustment';
      }

      return {
        id: order.id,
        receiptId: order.orderNo,
        type,
        amount: order.total,
        paymentType: isMultiplePayments ? 'mixed' : paymentType,
        date,
        time,
        customerName: '', // 顾客信息可能需要额外关联查询
        operatorName,
        shift: order.shift ? order.shift.type : '',
        storeName: order.channel ? order.channel.name : '',
        remark: order.note || ''
      };
    });

    // 如果指定了支付方式过滤
    if (viewType && viewType !== 'all') {
      items = items.filter(item => item.paymentType === viewType);
    }

    // 计算统计信息
    const totalAmount = items.reduce((sum, item) => sum + item.amount, 0);
    const positiveAmount = items
      .filter(item => item.amount > 0)
      .reduce((sum, item) => sum + item.amount, 0);
    const negativeAmount = items
      .filter(item => item.amount < 0)
      .reduce((sum, item) => sum + item.amount, 0);

    // 创建Excel工作簿和工作表
    const workbook = new Excel.Workbook();
    const worksheet = workbook.addWorksheet('收款明细表');

    // 添加标题
    worksheet.mergeCells('A1:K1');
    worksheet.getCell('A1').value = `哈喽啤鲜生收款明细表 - ${startDate} 至 ${endDate}`;
    worksheet.getCell('A1').font = { size: 16, bold: true };
    worksheet.getCell('A1').alignment = { horizontal: 'center' };

    // 添加基本统计数据
    worksheet.mergeCells('A2:K2');
    worksheet.getCell('A2').value = `总收款: ¥${positiveAmount.toFixed(2)} | 总退款: ¥${Math.abs(negativeAmount).toFixed(2)} | 净收入: ¥${totalAmount.toFixed(2)} | 记录总数: ${items.length}`;
    worksheet.getCell('A2').font = { size: 12 };
    worksheet.getCell('A2').alignment = { horizontal: 'center' };
    
    // 设置表头
    worksheet.addRow(['单号', '账目名称', '付款方式', '金额', '营业日', '操作时间', '顾客名称', '操作员', '班次', '门店', '备注']);
    
    // 设置表头样式
    const headerRow = worksheet.getRow(3);
    headerRow.eachCell((cell) => {
      cell.font = { bold: true };
      cell.alignment = { horizontal: 'center' };
      cell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFE0E0E0' }
      };
    });

    // 支付方式和收款类型名称映射
    const paymentTypeNames = {
      'cash': '现金',
      'wechat': '微信支付',
      'alipay': '支付宝',
      'card': '银行卡',
      'member': '会员卡',
      'mixed': '混合支付',
      'unknown': '未知方式'
    };

    const receiptTypeNames = {
      'sale': '销售收款',
      'refund': '退款',
      'recharge': '会员充值',
      'adjustment': '收款调整',
      'ar': 'AR账款',
      'ar-refund': 'AR退款'
    };

    // 添加数据行
    items.forEach((item, index) => {
      const rowData = [
        item.receiptId,
        receiptTypeNames[item.type] || item.type,
        paymentTypeNames[item.paymentType] || item.paymentType,
        item.amount,
        item.date,
        item.time,
        item.customerName,
        item.operatorName,
        item.shift === 'morning' ? '早班' : 
          item.shift === 'middle' ? '中班' : 
          item.shift === 'evening' ? '晚班' : item.shift,
        item.storeName,
        item.remark
      ];
      
      const row = worksheet.addRow(rowData);
      
      // 设置金额单元格格式
      const amountCell = row.getCell(4);
      amountCell.numFmt = '¥#,##0.00;[Red]-¥#,##0.00';
      
      // 设置负数行的样式
      if (item.amount < 0) {
        row.eachCell((cell) => {
          cell.font = { color: { argb: 'FFFF0000' } };
        });
      }
    });

    // 设置列宽
    worksheet.getColumn(1).width = 20; // 单号
    worksheet.getColumn(2).width = 15; // 账目名称
    worksheet.getColumn(3).width = 15; // 付款方式
    worksheet.getColumn(4).width = 15; // 金额
    worksheet.getColumn(5).width = 12; // 营业日
    worksheet.getColumn(6).width = 20; // 操作时间
    worksheet.getColumn(7).width = 15; // 顾客名称
    worksheet.getColumn(8).width = 15; // 操作员
    worksheet.getColumn(9).width = 10; // 班次
    worksheet.getColumn(10).width = 15; // 门店
    worksheet.getColumn(11).width = 20; // 备注

    try {
      // 设置响应头
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      const safeFilename = `receipts-${startDate}-${endDate}.xlsx`;
      res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(safeFilename)}"`);
      res.setHeader('X-Content-Type-Options', 'nosniff');
      
      // 将工作簿写入响应
      await workbook.xlsx.write(res);
    } catch (error) {
      console.error('导出Excel失败:', error);
      return res.status(500).json({
        status: 'error',
        message: '导出Excel失败',
        error: error.message
      });
    }
    
  } catch (error) {
    console.error('导出收款明细表失败:', error);
    res.status(500).json({
      status: 'error',
      message: '导出收款明细表失败',
      error: error.message
    });
  }
});

// 导出日期范围的日报
router.get('/daily/range/export', async (req, res) => {
  try {
    const { startDate, endDate } = req.query;
    
    if (!startDate || !endDate) {
      return res.status(400).json({
        status: 'error',
        message: '请提供起始日期和结束日期'
      });
    }
    
    console.log('收到普通导出请求，日期参数:', { startDate, endDate });
    
    // 验证日期格式 - 修改为更宽松的验证
    // 允许任何格式的日期字符串，只要能被Date对象解析
    const start = new Date(startDate);
    const end = new Date(endDate);
    
    // 检查日期是否有效
    if (isNaN(start.getTime()) || isNaN(end.getTime())) {
      return res.status(400).json({
        status: 'error',
        message: '无效的日期'
      });
    }
    
    // 格式化日期为YYYY-MM-DD格式
    const formattedStartDate = start.toISOString().split('T')[0];
    const formattedEndDate = end.toISOString().split('T')[0];
    
    console.log('格式化后的日期:', { formattedStartDate, formattedEndDate });
    
    // 设置时间范围
    start.setHours(0, 0, 0, 0);
    end.setHours(23, 59, 59, 999);
    
    // 查询该日期范围内的订单
    const orders = await prisma.order.findMany({
      where: {
        createdAt: {
          gte: start,
          lte: end
        },
        status: {
          in: ['completed', 'paid']
        }
      },
      include: {
        items: {
          include: {
            product: true
          }
        },
        channel: true,
        payments: {
          select: {
            id: true,
            orderId: true,
            method: true,
            amount: true,
            status: true,
            createdAt: true,
            updatedAt: true
          }
        },
        user: true
      }
    });
    
    // 按日期分组
    const dailyData = {};
    orders.forEach(order => {
      const dateStr = order.createdAt.toISOString().split('T')[0];
      
      if (!dailyData[dateStr]) {
        dailyData[dateStr] = {
          date: dateStr,
          orders: [],
          totalSales: 0,
          orderCount: 0
        };
      }
      
      dailyData[dateStr].orders.push(order);
      dailyData[dateStr].totalSales += order.total;
      dailyData[dateStr].orderCount += 1;
    });
    
    // 创建Excel工作簿和工作表
    const workbook = new Excel.Workbook();
    const worksheet = workbook.addWorksheet('日期范围报表');
    
    // 添加标题
    worksheet.mergeCells('A1:G1');
    worksheet.getCell('A1').value = `哈喽啤鲜生销售日报 - ${startDate} 至 ${endDate}`;
    worksheet.getCell('A1').font = { size: 16, bold: true };
    worksheet.getCell('A1').alignment = { horizontal: 'center' };
    
    // 添加汇总数据
    const totalSales = orders.reduce((sum, order) => sum + order.total, 0);
    const orderCount = orders.length;
    const averageOrder = orderCount > 0 ? totalSales / orderCount : 0;
    
    worksheet.addRow(['总销售额', `¥${totalSales.toFixed(2)}`, '', '订单总数', orderCount, '', '']);
    worksheet.addRow(['平均客单价', `¥${averageOrder.toFixed(2)}`, '', '日期范围', `${startDate} 至 ${endDate}`, '', '']);
    
    worksheet.addRow(['']);
    
    // 添加每日销售数据
    worksheet.addRow(['日期', '销售额', '订单数', '客单价', '', '', '']);
    const headerRow = worksheet.lastRow;
    headerRow.eachCell((cell) => {
      cell.font = { bold: true };
      cell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFE0E0E0' }
      };
    });
    
    // 按日期排序
    const sortedDates = Object.keys(dailyData).sort();
    
    sortedDates.forEach(dateStr => {
      const data = dailyData[dateStr];
      const avgOrder = data.orderCount > 0 ? data.totalSales / data.orderCount : 0;
      worksheet.addRow([
        dateStr,
        data.totalSales,
        data.orderCount,
        avgOrder,
        '',
        '',
        ''
      ]);
      
      // 设置金额单元格格式
      const row = worksheet.lastRow;
      row.getCell(2).numFmt = '¥#,##0.00';
      row.getCell(4).numFmt = '¥#,##0.00';
    });
    
    // 添加合计行
    worksheet.addRow([
      '合计',
      totalSales,
      orderCount,
      averageOrder,
      '',
      '',
      ''
    ]);
    const totalRow = worksheet.lastRow;
    totalRow.eachCell((cell, colNumber) => {
      if (colNumber <= 4) {
        cell.font = { bold: true };
      }
    });
    totalRow.getCell(2).numFmt = '¥#,##0.00';
    totalRow.getCell(4).numFmt = '¥#,##0.00';
    
    worksheet.addRow(['']);
    worksheet.addRow(['']);
    
    // 添加支付方式统计
    worksheet.addRow(['支付方式统计']);
    worksheet.lastRow.getCell(1).font = { bold: true, size: 14 };
    
    worksheet.addRow(['支付方式', '金额', '笔数', '', '', '', '']);
    const paymentHeaderRow = worksheet.lastRow;
    paymentHeaderRow.eachCell((cell, colNumber) => {
      if (colNumber <= 3) {
        cell.font = { bold: true };
        cell.fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: 'FFE0E0E0' }
        };
      }
    });
    
    // 统计支付方式
    const paymentMethods = {};
    orders.forEach(order => {
      if (!order.payments || order.payments.length === 0) return;
      
      order.payments.forEach(payment => {
        const method = payment.method || 'unknown';
        
        if (!paymentMethods[method]) {
          paymentMethods[method] = {
            method,
            amount: 0,
            count: 0
          };
        }
        
        paymentMethods[method].amount += payment.amount;
        paymentMethods[method].count += 1;
      });
    });
    
    // 添加支付方式数据
    Object.values(paymentMethods).forEach(payment => {
      worksheet.addRow([
        getPaymentMethodName(payment.method),
        payment.amount,
        payment.count,
        '',
        '',
        '',
        ''
      ]);
      
      worksheet.lastRow.getCell(2).numFmt = '¥#,##0.00';
    });
    
    // 设置列宽
    worksheet.getColumn(1).width = 15;
    worksheet.getColumn(2).width = 15;
    worksheet.getColumn(3).width = 10;
    worksheet.getColumn(4).width = 15;
    
    try {
      // 设置响应头
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      const safeFilename = `哈喽啤鲜生销售日报-${startDate}-${endDate}.xlsx`;
      res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(safeFilename)}"`);
      res.setHeader('X-Content-Type-Options', 'nosniff');
      
      // 将工作簿写入响应
      await workbook.xlsx.write(res);
    } catch (err) {
      console.error('Excel生成失败:', err);
      return res.status(500).json({
        status: 'error',
        message: '报表生成失败',
        error: err.message
      });
    }
  } catch (error) {
    console.error('导出日期范围日报失败:', error);
    res.status(500).json({
      status: 'error',
      message: '导出日期范围日报失败',
      error: error.message
    });
  }
});

// 辅助函数：获取支付方式显示名称
function getPaymentMethodName(method) {
  const methods = {
    'cash': '现金',
    'wechat': '微信支付',
    'alipay': '支付宝',
    'card': '银行卡',
    'member': '会员卡',
    'coupon': '优惠券',
    'mixed': '混合支付',
    'unknown': '未知方式'
  };
  
  return methods[method] || method;
}

module.exports = router; 